package com.ckm.aop;

import com.alibaba.fastjson2.JSONArray;
import com.ckm.annotation.FindRedis;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
@Component
public class FindRedisAspect {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Around("@annotation(com.ckm.annotation.FindRedis)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        FindRedis findRedis = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(FindRedis.class);
        String key = findRedis.key();
        if (key.isEmpty()){
            key = signature.getName();
        }
        String params = JSONArray.toJSONString(joinPoint.getArgs());
        String redisKey = key + "::" + params;
        log.info(redisKey);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(redisKey))){
            return redisTemplate.opsForValue().get(redisKey);
        }
        Object proceed = joinPoint.proceed();
        int expire = findRedis.expire();
        if (expire==0){
            expire = (int) (Math.random()*10+1);
        }
        log.info("缓存时间：{}m",expire);
        redisTemplate.opsForValue().set(redisKey, proceed,expire, TimeUnit.MINUTES);
        return proceed;
    }
}
